package com.mystudy.leetcode.problem.hash.p_350;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 周志龙
 * @Email 15216876513@163.com
 * @Date on 2019/7/29 22:19
 * @Description 两个数组的交集 II
 */
public class Solution {
    private static final Logger LOGGER = LoggerFactory.getLogger(Solution.class);
    @Test
    public void test(){
        int [] nums1 = new int[]{4,7,9,7,6,7};
        int [] nums2 = new int[]{5,0,0,6,1,6,2,2,4};
        int[] intersect = intersect(nums1, nums2);
        LOGGER.debug("intersect = [{}]",intersect);

    }


    public int[] intersect(int[] nums1, int[] nums2) {
        List<Integer> list = new ArrayList<>();
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums1.length; i++) {
            if(!map.containsKey(nums1[i])){
                map.put(nums1[i],1);
            }else{
                map.put(nums1[i],map.get(nums1[i])+1);
            }
        }
        for (int i = 0; i < nums2.length; i++) {
            int key = nums2[i];
            Integer value = map.get(key);
            if(value != null && value >0){
                map.put(key,value-1);
                list.add(key);
            }
        }
        int [] result = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            result[i] = list.get(i);
        }
        return result;
    }
}
